<template>
  <div class="check-board-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Grid /></el-icon>
          <div class="header-text">
            <h2>盘点任务看板</h2>
            <p>可视化管理盘点任务流程</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button-group>
            <el-button type="primary">
              <el-icon><Grid /></el-icon>
              看板视图
            </el-button>
            <el-button @click="$router.push('/inventory/check-tasks')">
              <el-icon><List /></el-icon>
              列表视图
            </el-button>
          </el-button-group>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            新建任务
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#909399"><Document /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ pendingTasks.length }}</div>
            <div class="stat-label">待盘点</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#409EFF"><Loading /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ inProgressTasks.length }}</div>
            <div class="stat-label">盘点中</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#E6A23C"><View /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ reviewTasks.length }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#67C23A"><CircleCheck /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ completedTasks.length }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 看板区域 -->
    <div class="board-wrapper">
      <!-- 待盘点列 -->
      <div class="board-column">
        <div class="column-header pending-header">
          <div class="column-title">
            <el-icon><Document /></el-icon>
            <span>待盘点</span>
            <el-badge :value="pendingTasks.length" class="column-badge" />
          </div>
          <el-button link @click="addTaskToColumn('pending')">
            <el-icon><Plus /></el-icon>
          </el-button>
        </div>
        <div 
          class="column-content"
          @drop="handleDrop($event, 'pending')"
          @dragover.prevent
          @dragenter.prevent
        >
          <transition-group name="card">
            <div
              v-for="task in pendingTasks"
              :key="task.id"
              class="task-card pending-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @dragend="handleDragEnd"
            >
              <div class="card-header">
                <div class="card-title">{{ task.taskName }}</div>
                <el-dropdown @command="handleCardAction($event, task)">
                  <el-button link size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">查看</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="card-body">
                <div class="card-info">
                  <el-icon><House /></el-icon>
                  <span>{{ task.warehouseName }}</span>
                </div>
                <div class="card-info">
                  <el-icon><User /></el-icon>
                  <span>{{ task.responsiblePerson }}</span>
                </div>
                <div class="card-info">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ task.planStartDate }}</span>
                </div>
              </div>
              <div class="card-footer">
                <el-tag size="small">{{ task.type }}</el-tag>
              </div>
            </div>
          </transition-group>
          <el-empty v-if="pendingTasks.length === 0" description="暂无待盘点" :image-size="80" />
        </div>
      </div>

      <!-- 盘点中列 -->
      <div class="board-column">
        <div class="column-header progress-header">
          <div class="column-title">
            <el-icon><Loading /></el-icon>
            <span>盘点中</span>
            <el-badge :value="inProgressTasks.length" class="column-badge" />
          </div>
        </div>
        <div 
          class="column-content"
          @drop="handleDrop($event, 'inProgress')"
          @dragover.prevent
          @dragenter.prevent
        >
          <transition-group name="card">
            <div
              v-for="task in inProgressTasks"
              :key="task.id"
              class="task-card progress-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @dragend="handleDragEnd"
            >
              <div class="card-header">
                <div class="card-title">{{ task.taskName }}</div>
                <el-dropdown @command="handleCardAction($event, task)">
                  <el-button link size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">查看</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="card-body">
                <div class="card-info">
                  <el-icon><House /></el-icon>
                  <span>{{ task.warehouseName }}</span>
                </div>
                <div class="card-info">
                  <el-icon><User /></el-icon>
                  <span>{{ task.responsiblePerson }}</span>
                </div>
                <div class="card-progress">
                  <el-progress :percentage="task.progress" :stroke-width="8" />
                </div>
              </div>
              <div class="card-footer">
                <el-tag size="small">{{ task.type }}</el-tag>
                <span class="time-info">开始于 {{ task.actualStartDate }}</span>
              </div>
            </div>
          </transition-group>
          <el-empty v-if="inProgressTasks.length === 0" description="暂无盘点中" :image-size="80" />
        </div>
      </div>

      <!-- 待审核列 -->
      <div class="board-column">
        <div class="column-header review-header">
          <div class="column-title">
            <el-icon><View /></el-icon>
            <span>待审核</span>
            <el-badge :value="reviewTasks.length" class="column-badge" />
          </div>
        </div>
        <div 
          class="column-content"
          @drop="handleDrop($event, 'review')"
          @dragover.prevent
          @dragenter.prevent
        >
          <transition-group name="card">
            <div
              v-for="task in reviewTasks"
              :key="task.id"
              class="task-card review-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @dragend="handleDragEnd"
            >
              <div class="card-header">
                <div class="card-title">{{ task.taskName }}</div>
                <el-dropdown @command="handleCardAction($event, task)">
                  <el-button link size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">查看</el-dropdown-item>
                      <el-dropdown-item command="approve">审核</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="card-body">
                <div class="card-info">
                  <el-icon><House /></el-icon>
                  <span>{{ task.warehouseName }}</span>
                </div>
                <div class="card-info">
                  <el-icon><User /></el-icon>
                  <span>{{ task.responsiblePerson }}</span>
                </div>
                <div class="card-diff">
                  <span class="diff-label">盈亏金额：</span>
                  <span :class="getDiffClass(task.totalDiffAmount)">
                    {{ task.totalDiffAmount > 0 ? '+' : '' }}¥{{ Math.abs(task.totalDiffAmount).toLocaleString() }}
                  </span>
                </div>
              </div>
              <div class="card-footer">
                <el-tag size="small">{{ task.type }}</el-tag>
                <span class="time-info">{{ task.actualEndDate }}</span>
              </div>
            </div>
          </transition-group>
          <el-empty v-if="reviewTasks.length === 0" description="暂无待审核" :image-size="80" />
        </div>
      </div>

      <!-- 已完成列 -->
      <div class="board-column">
        <div class="column-header completed-header">
          <div class="column-title">
            <el-icon><CircleCheck /></el-icon>
            <span>已完成</span>
            <el-badge :value="completedTasks.length" class="column-badge" />
          </div>
          <el-button link @click="handleArchive" v-if="completedTasks.length > 0">
            <el-icon><FolderOpened /></el-icon>
          </el-button>
        </div>
        <div 
          class="column-content"
          @drop="handleDrop($event, 'completed')"
          @dragover.prevent
          @dragenter.prevent
        >
          <transition-group name="card">
            <div
              v-for="task in completedTasks"
              :key="task.id"
              class="task-card completed-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @dragend="handleDragEnd"
            >
              <div class="card-header">
                <div class="card-title">{{ task.taskName }}</div>
                <el-dropdown @command="handleCardAction($event, task)">
                  <el-button link size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">查看</el-dropdown-item>
                      <el-dropdown-item command="archive">归档</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="card-body">
                <div class="card-info">
                  <el-icon><House /></el-icon>
                  <span>{{ task.warehouseName }}</span>
                </div>
                <div class="card-info">
                  <el-icon><CircleCheckFilled color="#67C23A" /></el-icon>
                  <span>{{ task.actualEndDate }}</span>
                </div>
              </div>
              <div class="card-footer">
                <el-tag size="small" type="success">{{ task.type }}</el-tag>
              </div>
            </div>
          </transition-group>
          <el-empty v-if="completedTasks.length === 0" description="暂无已完成" :image-size="80" />
        </div>
      </div>
    </div>

    <!-- 新建任务对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建盘点任务" width="600px">
      <el-form :model="taskForm" label-width="120px">
        <el-form-item label="任务名称">
          <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="盘点类型">
          <el-select v-model="taskForm.type" style="width: 100%">
            <el-option label="全盘" value="全盘" />
            <el-option label="抽盘" value="抽盘" />
            <el-option label="循环盘点" value="循环盘点" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点仓库">
          <el-select v-model="taskForm.warehouseId" style="width: 100%">
            <el-option label="主仓库" :value="1" />
            <el-option label="分仓A" :value="2" />
            <el-option label="分仓B" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="taskForm.responsiblePerson" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="初始状态">
          <el-select v-model="taskForm.status" style="width: 100%">
            <el-option label="待盘点" value="pending" />
            <el-option label="立即开始" value="inProgress" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateTask">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid, List, Plus, Document, Loading, View, CircleCheck, More,
  House, User, Calendar, CircleCheckFilled, FolderOpened
} from '@element-plus/icons-vue'

const router = useRouter()

// 状态
const showCreateDialog = ref(false)
const draggedTask = ref(null)

// 任务表单
const taskForm = ref({
  taskName: '',
  type: '全盘',
  warehouseId: 1,
  responsiblePerson: '',
  status: 'pending'
})

// 任务数据
const tasks = ref([
  {
    id: 1,
    taskNo: 'CHK202401150001',
    taskName: '2024年1月全盘任务',
    type: '全盘',
    warehouseId: 1,
    warehouseName: '主仓库',
    status: 'pending',
    planStartDate: '2024-01-15',
    responsiblePerson: '张三'
  },
  {
    id: 2,
    taskNo: 'CHK202401160002',
    taskName: '高价值商品抽盘',
    type: '抽盘',
    warehouseId: 1,
    warehouseName: '主仓库',
    status: 'inProgress',
    actualStartDate: '2024-01-16 08:30',
    responsiblePerson: '李四',
    progress: 45
  },
  {
    id: 3,
    taskNo: 'CHK202401140003',
    taskName: '分仓A定期盘点',
    type: '循环盘点',
    warehouseId: 2,
    warehouseName: '分仓A',
    status: 'review',
    actualEndDate: '2024-01-14 17:00',
    responsiblePerson: '王五',
    totalDiffAmount: -15000
  },
  {
    id: 4,
    taskNo: 'CHK202401130004',
    taskName: '耗材专项盘点',
    type: '抽盘',
    warehouseId: 1,
    warehouseName: '主仓库',
    status: 'completed',
    actualEndDate: '2024-01-13 16:30',
    responsiblePerson: '赵六'
  }
])

// 计算属性 - 按状态分组
const pendingTasks = computed(() => 
  tasks.value.filter(task => task.status === 'pending')
)

const inProgressTasks = computed(() => 
  tasks.value.filter(task => task.status === 'inProgress')
)

const reviewTasks = computed(() => 
  tasks.value.filter(task => task.status === 'review')
)

const completedTasks = computed(() => 
  tasks.value.filter(task => task.status === 'completed')
)

// 拖拽处理
const handleDragStart = (event, task) => {
  draggedTask.value = task
  event.target.style.opacity = '0.5'
}

const handleDragEnd = (event) => {
  event.target.style.opacity = '1'
}

const handleDrop = (event, newStatus) => {
  if (!draggedTask.value) return
  
  const oldStatus = draggedTask.value.status
  if (oldStatus === newStatus) return
  
  // 更新状态
  draggedTask.value.status = newStatus
  
  // 根据状态更新相应字段
  if (newStatus === 'inProgress' && !draggedTask.value.actualStartDate) {
    draggedTask.value.actualStartDate = new Date().toLocaleString()
    draggedTask.value.progress = 0
  }
  
  if (newStatus === 'completed' && !draggedTask.value.actualEndDate) {
    draggedTask.value.actualEndDate = new Date().toLocaleString()
    draggedTask.value.progress = 100
  }
  
  ElMessage.success(`任务已移动到${getStatusName(newStatus)}`)
  draggedTask.value = null
}

// 卡片操作
const handleCardAction = (command, task) => {
  if (command === 'view') {
    router.push(`/inventory/check-tasks`)
  } else if (command === 'edit') {
    ElMessage.info('编辑功能')
  } else if (command === 'delete') {
    handleDelete(task)
  } else if (command === 'approve') {
    handleApprove(task)
  } else if (command === 'archive') {
    handleArchiveTask(task)
  }
}

const handleDelete = (task) => {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = tasks.value.findIndex(t => t.id === task.id)
    if (index > -1) {
      tasks.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

const handleApprove = (task) => {
  ElMessageBox.confirm('确定要审核通过该任务吗？', '提示', {
    type: 'info'
  }).then(() => {
    task.status = 'completed'
    ElMessage.success('审核通过')
  }).catch(() => {})
}

const handleArchiveTask = (task) => {
  ElMessage.success('归档成功')
}

const handleArchive = () => {
  ElMessageBox.confirm('确定要归档所有已完成的任务吗？', '提示', {
    type: 'info'
  }).then(() => {
    ElMessage.success('归档成功')
  }).catch(() => {})
}

const addTaskToColumn = (status) => {
  taskForm.value.status = status
  showCreateDialog.value = true
}

const handleCreateTask = () => {
  const warehouseName = { 1: '主仓库', 2: '分仓A', 3: '分仓B' }[taskForm.value.warehouseId]
  
  tasks.value.unshift({
    id: Date.now(),
    taskNo: 'CHK' + Date.now(),
    taskName: taskForm.value.taskName,
    type: taskForm.value.type,
    warehouseId: taskForm.value.warehouseId,
    warehouseName: warehouseName,
    status: taskForm.value.status,
    planStartDate: new Date().toLocaleDateString(),
    responsiblePerson: taskForm.value.responsiblePerson,
    progress: 0
  })
  
  showCreateDialog.value = false
  ElMessage.success('创建成功')
}

// 工具函数
const getStatusName = (status) => {
  const map = {
    pending: '待盘点',
    inProgress: '盘点中',
    review: '待审核',
    completed: '已完成'
  }
  return map[status] || status
}

const getDiffClass = (value) => {
  if (value > 0) return 'profit-text'
  if (value < 0) return 'loss-text'
  return ''
}
</script>

<style scoped>
.check-board-container {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.header-card {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.board-wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.board-column {
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.column-header {
  padding: 16px;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
}

.pending-header {
  background: #f4f4f5;
}

.progress-header {
  background: #fef0e6;
}

.review-header {
  background: #e6f7ff;
}

.completed-header {
  background: #f0f9ff;
}

.column-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 15px;
  color: #303133;
}

.column-badge {
  margin-left: 8px;
}

.column-content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  min-height: 200px;
}

.column-content::-webkit-scrollbar {
  width: 6px;
}

.column-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.task-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  cursor: move;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  border-left: 3px solid transparent;
}

.task-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.pending-card {
  border-left-color: #909399;
}

.progress-card {
  border-left-color: #409EFF;
}

.review-card {
  border-left-color: #E6A23C;
}

.completed-card {
  border-left-color: #67C23A;
  opacity: 0.85;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.card-title {
  flex: 1;
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
}

.card-body {
  margin-bottom: 12px;
}

.card-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
  margin-bottom: 6px;
}

.card-progress {
  margin-top: 8px;
}

.card-diff {
  margin-top: 8px;
  font-size: 13px;
}

.diff-label {
  color: #909399;
}

.profit-text {
  color: #67C23A;
  font-weight: 600;
}

.loss-text {
  color: #F56C6C;
  font-weight: 600;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-info {
  font-size: 12px;
  color: #909399;
}

.card-enter-active,
.card-leave-active {
  transition: all 0.3s ease;
}

.card-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.card-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

@media (max-width: 1400px) {
  .board-wrapper {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .board-wrapper {
    grid-template-columns: 1fr;
  }
  
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

